package example

import (
	"fmt"
	"runtime"
	"sync"
	"time"
)
var i int64 = 0

func T3(){
	runtime.GOMAXPROCS(2)
	go func() {
		for  {
			fmt.Println("i is", i)
			time.Sleep(time.Second)
		}
	}()
	for{
		i++
	}
}
//T3优化版, 增加互斥锁,这是"共享内存来通信"
func T3_1(){
	runtime.GOMAXPROCS(2)
	var mu sync.Mutex
	go func() {
		for  {
			mu.Lock()
			fmt.Println("i is", i)
			mu.Unlock()
			time.Sleep(time.Second)
		}
	}()
	for  {
		mu.Lock()
		i++
		mu.Unlock()
	}
}
//T3 优化版,增加 chan,这是"通过通信来共享内存"
func T3_2(){
	runtime.GOMAXPROCS(2)
	ch := make(chan int64)
	go func() {
		for  {
			fmt.Println("i is", <-ch)
			time.Sleep(time.Second)
		}
	}()
	for{
		i++
		ch<- i
	}
}